/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LianBao
 * Date: 2024-04-02
 * Time: 20:40
 */

class TreeNode {

    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {

    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }

}

public class OJ {
    /**
     * 判断是不是两棵相同的树
     *
     * @param p 第一棵树的根节点
     * @param q 第二棵树的根节点
     * @return 如果相同返回true, 否则返回false
     */
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null && q == null) {
            return true;
        }
        if (p == null || q == null) {
            return false;
        }
        //如果根节点的val不同
        if (p.val != q.val) {
            return false;
        } else {
            return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);//判断左右结点是否相等
        }
    }

    /**
     * 判断一棵树是否为另一棵树的子树
     *
     * @param root    第一棵树的根节点
     * @param subRoot 第二棵树的根节点
     * @return 是返回true, 否则返回false
     */
    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        if (subRoot == null) {
            return true;
        }
        if (root == null) {
            return false;
        }

        return isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot) || isSameTree(root, subRoot);
    }

    /**
     * 翻转二叉树
     * @param root 树的根节点
     * @return 返回翻转后的根节点
     */
    public TreeNode invertTree(TreeNode root) {
        if(root==null) {
            return root;
        }
        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;
        //先反转左子树 再反转右子树
        invertTree(root.left);
        invertTree(root.right);
        return root;
    }
}
